package com.hermit.qmst.UI.activitys;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.hermit.qmst.R;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.Preferences;
import com.hermit.qmst.tools.RequestHttp;
import com.hermit.qmst.tools.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/1/2 0002.
 */
@ContentView(R.layout.new_activity_login)
public class LoginActivity extends Activity implements View.OnClickListener {
    @ViewInject(R.id.iv_back)
    ImageView mIvBack;
    @ViewInject(R.id.tv_title)
    TextView mTvTitle;
    @ViewInject(R.id.et_name)
    EditText mEtName;
    @ViewInject(R.id.et_pwd)
    EditText mEtPwd;
    @ViewInject(R.id.sp_code)
    Spinner mSpCode;
    @ViewInject(R.id.tv_forget_pwd)
    TextView mTvForgetPwd;
    @ViewInject(R.id.tv_register)
    TextView mTvRegister;

    @ViewInject(R.id.bt_save)
    Button mBtSave;
    private String loginUrl = Common.mUrl + "szdh/login.php";
    private String getAcctsUrl = Common.mUrl + "szdh/getAccts.php?username=";
    private List<String> acctNames = new ArrayList<>();
    private String acctName = "全民商通";
    private String mPhone;
    private String mPassword;
    private ArrayAdapter<String> adapter;
    public static boolean isRegister = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        mTvTitle.setText("登录");
        mIvBack.setVisibility(View.INVISIBLE);
        mTvForgetPwd.setOnClickListener(this);
        mTvRegister.setOnClickListener(this);
        mBtSave.setOnClickListener(this);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, acctNames);
        mEtName.addTextChangedListener(new EditChangedListener());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    }

    private class EditChangedListener implements TextWatcher {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (Utils.isMobileNO(s.toString())) {
                getAccts();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(LoginActivity.this, VerifyPhoneActivity.class);
        switch (v.getId()) {
            case R.id.tv_forget_pwd:
                isRegister = false;
                startActivity(intent);
                break;
            case R.id.tv_register:
                isRegister = true;
                startActivity(intent);
                break;
            case R.id.bt_save:
                login();
                break;
        }

    }

    private void getAccts() {
        String phone = mEtName.getText().toString().trim();
        RequestHttp.getHttp(this, getAcctsUrl + phone, new RequestHttp.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject) {
                try {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    if (jsonObject.getBoolean("state") && jsonArray.length() > 0) {
                        acctNames.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            acctNames.add(jsonArray.getJSONObject(i).getString("acctname"));
                        }
                        mSpCode.setAdapter(adapter);
                    } else {
                        Toast.makeText(LoginActivity.this, "该手机未注册，请先注册", Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void login() {
        mPhone = mEtName.getText().toString().trim();
        mPassword = mEtPwd.getText().toString().trim();
        if (acctNames.size() == 0) {
            Toast.makeText(LoginActivity.this, "请填写正确的信息", Toast.LENGTH_SHORT).show();
        } else {
            try {
                acctName = URLEncoder.encode(mSpCode.getSelectedItem().toString(), "utf-8");
            } catch (UnsupportedEncodingException e) {

            }
            String url = loginUrl + "?username=" + mPhone + "&password=" + mPassword + "&acct=" + acctName;
            RequestHttp.getHttp(this, url, new RequestHttp.HttpCallBack() {
                @Override
                public void successHttp(JSONObject jsonObject) {
                    Preferences p = new Preferences(LoginActivity.this);
                    try {
                        if (jsonObject.getBoolean("state")) {
                            JSONObject object = jsonObject.getJSONArray("data").getJSONObject(0);
                            p.setPreferenceStringValue(Preferences.MY_PHONE, mPhone);
                            p.setPreferenceStringValue(Preferences.MY_PASSWORD, mPassword);
                            //直拨账号
                            p.setPreferenceStringValue(Preferences.SIP_ACCOUNT, "500" + mPhone);
                            p.setPreferenceStringValue(Preferences.SIP_AGENT, object.getString("agent_id"));
                            p.setPreferenceStringValue(Preferences.SIP_AGENT_THIRD, object.getString("agent_id_third"));
                            p.setPreferenceStringValue(Preferences.USER_ID, object.getString("id"));
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            LoginActivity.this.finish();
                        } else {
                            Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
